var util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
import WxValidate from '../../../lib/wx-validate/WxValidate.js'
//获取应用实例
const app = getApp();
var that;
var timer = null;
Page({
  data: {
    form:{
      principalMobile: '',
      verifiCode: '',
      captchaKey:'',
    },
    btnTxt:'获取验证码',
    isSendVerifiCode:false,
    jumpPage: '',
    needJump: false
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    that = this;
    if (options.page) {
      that.setData({
        jumpPage: decodeURIComponent(options.page),
        needJump: true
      });
    }
    that.initValidate();
  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示
    that.refreshCode();
  },
  onHide: function () {
    // 页面隐藏
    if (timer) clearInterval(timer);
  },
  onUnload: function () {
    // 页面关闭
    if (timer) clearInterval(timer);
  },
  sendCode: function () {
    if (that.data.isSendVerifiCode)return true;
    if (!util.isValidPhone(that.data.form.principalMobile)) {
      util.confirm.modal('请填写正确的手机号！');
    } else {
      var tmpTxt = that.data.btnTxt;
      app.postForm(api.SendVerifiCode, { phone: that.data.form.principalMobile, isAllow: true}).then(rsp => {
        let captchaKey = rsp.captchaKey;
        that.setData({
          btnTxt: '已发送......',
          isSendVerifiCode: true,
          'form.captchaKey': captchaKey
        });
        var time = 60;
        timer = setInterval(function () {
          time--;
          that.setData({
            btnTxt: time + 's'
          });
          if (time == 0) {
            time = 60;
            that.setData({
              btnTxt: tmpTxt,
              isSendVerifiCode: false
            });
            clearInterval(timer);
          }
        }, 1000);
      }).catch((err) => {
        console.log('err', err);
      });
    }
  },
  refreshCode: function () {
    util.login().then((res) => {
      that.setData({
        code: res.code
      });
    }).catch((err) => {
      console.log("未登录报异常：", err);
    });
  },
  submitForm(e) {
    const params = e.detail.value
    //console.log(params)
    // 传入表单数据，调用验证方法
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      util.confirm.modal(error.msg);
      return false
    }
    
    let phoneInfo = that.data.form;
    phoneInfo.code = that.data.code;
    phoneInfo.isAllow = true;
    app.post(api.LoginByAccPhone, phoneInfo).then(rsp => {
      wx.clearStorage(); //清除缓存
      let res = rsp.data;
      if (!res.isSubmitAuthInfo) { //还未提交认证信息
        util.confirm.modalOk('您的信息还没有注册！');
      } else {
        //是否授权基本信息(微信头像，昵称)
        if (res.isAuthBaseInfo) {
          app.globalData.isAuthBaseInfo = true;
          app.globalData.userInfo = res.userInfo;
          wx.setStorageSync('userInfo', res.userInfo);
          wx.setStorageSync('isAuthBaseInfo', true);
        }else{
          wx.setStorageSync('isAuthBaseInfo', false);
        }
        //实名是否认证成功
        app.globalData.isCert = res.isCert;
        wx.setStorageSync('isCert', res.isCert);
        
        wx.setStorageSync('isTouristRent', res.isTouristRent);
        app.isTouristRent = res.isTouristRent;
        wx.setStorageSync('phoneNumber', res.phoneNumber);
        wx.setStorageSync('tenantNo', res.tenantNo);
        wx.setStorageSync('token', res.token);
        app.globalData.phoneNumber = res.phoneNumber;
        app.globalData.tenantNo = res.tenantNo;
        app.globalData.hasLogin = true;
        if (that.data.needJump && that.data.jumpPage.indexOf('pages/index/index') == -1) {
          wx.redirectTo({
            url: '/' + that.data.jumpPage,
          })
        } else {
          //console.log('pages', getCurrentPages());
          var p = getCurrentPages()[0];
          if (!p.data.isUpdate) {
            p.setData({ isUpdate: true });
          }
          wx.switchTab({
            url: '/pages/index/index',
          })
        }
      }
    }).catch((err) => {
      console.log('err', err);
      that.refreshCode();
    });
  },
  bindInput: function (e) {
    let name = e.currentTarget.dataset.name;
    let changeVal = {};
    changeVal[name] = e.detail.value;
    that.setData(changeVal);
  },
  clearInput: function (e) {
    let name = e.currentTarget.id;
    let changeVal = {};
    changeVal[name] = '';
    that.setData(changeVal);
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      principalMobile: {
        required: true,
        tel: true,
      },
      verifiCode: {
        required: true,
        number:true,
        minlength: 6,
        maxlength: 6,
      },
    }

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      principalMobile: {
        required: '请输入手机号',
        tel: '手机号格式错误'
      },
      verifiCode: {
        required: '请输入验证码',
        number: '验证码为6为数字',
        minlength: '验证码为6为数字',
        maxlength: '验证码为6为数字',
      },
    }
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
})